//
//  FirstViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 2/12/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "FirstViewController.h"

#import "ShowWorksViewController.h"
#import "AppointmentShootViewController.h"
#import "ChooseCameraManViewController.h"
#import "ChooseImageRootViewController.h"
#import "ChooseImageViewController.h"
#import "WuLiuViewController.h"
// 选择城市
#import "ChooseCityViewController.h"

#import "SuiJiaoSuiDaoViewController.h"
#import "SynthesizeDetailsViewController.h"

#import "ChooseEmplTimeViewController.h"

#import "ShowWebViewController.h"

#import "FreePaiViewController.h"
#define image_tag 10000

@interface FirstViewController ()
{
    NSString * downUrl;
    
    NSMutableArray * urlArray;

    int clickcount;
    
    UIButton * btn1;
    UIButton * btn2;
    UIButton * btn3;
    UIButton * btn4;
    
    UILabel * cityLB;
}
@end

@implementation FirstViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    locService.delegate  =self;
    [locService startUserLocationService];

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    locService.delegate = nil;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    clickcount = 0;
    btn1.selected = NO;
    btn2.selected = NO;
    btn3.selected = NO;
    btn4.selected = NO;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}


- (void)viewDidLoad{
    [super viewDidLoad];
    
    clickcount= 0;
    
    urlArray = [[NSMutableArray alloc] init];
    
    self.leftBtn.hidden = YES;
    CGFloat xheight = IOS7?20:0;
    // 小鬼当家图片
    UIImageView * hiv = [UIImageView initImageViewRect:CGRectMake(UI_SCREEN_WIDTH-100-9,xheight, 100, 44) andImage:LOADIMAGE(@"sy_head@2x") andUserInteractionEnabled:YES];
    [self.navigationBarView addSubview:hiv];
    // 左侧“北京”字体
    cityLB = [UILabel initLabelText:@"北京" andRect:CGRectMake(12, xheight, 60, 44) andBackGroudColor:mClearColor andTextFont:[UIFont systemFontOfSize:15] andTextColor:UIColorFromRGB(0xff6800) andTextAlignment:NSTextAlignmentLeft];
    [self.navigationBarView addSubview:cityLB];
    // 左侧“北京”字体 右边的图片
    UIImageView * jiv = [UIImageView initImageViewRect:CGRectMake(42,(44-8)/2.0f+xheight + 2,10,5) andImage:LOADIMAGE(@"cityimg@2x") andUserInteractionEnabled:YES];
    [self.navigationBarView addSubview:jiv];
    
    UIButton * chooseBtn = [self createButtonOnNavigationWithRect:CGRectMake(0, 0, 50, 44) normalImg:nil highlightImg:nil];
    [chooseBtn addTarget:self action:@selector(chooseBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:chooseBtn];

    
    downUrl = [[NSString alloc]init];
    
    
    backScrollView = [[UIScrollView alloc] initWithFrame:self.contentView.bounds];
    [self.contentView addSubview:backScrollView];

    banner = [[PageScrollView alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 167) andPageControllRect:CGRectMake(0,110+30, UI_SCREEN_WIDTH-240, 25)];

    banner.delegate = self;
    [backScrollView addSubview:banner];
    
    if (iPhone5){
        [self initViewsWithHeight:167];
    }else{
        banner.frame = CGRectMake(0, 0, UI_SCREEN_WIDTH, 255/2.0f);
        [self initViewsWithHeight:255/2.0f];
    }
    
    [self getBannersData];
    [self updateVerson];

    locService = [[BMKLocationService alloc] init];
    
    if (ISLOGING) {
        [self autologinAction];
    }
}

#pragma mark
#pragma mark 自动登录
-(void)autologinAction
{
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    NSString * urlStr = @"http://www.meike365.cn/index.php?m=Api&c=Index&a=autoLogin";   //正式的
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    urlStr = [NSString stringWithFormat:@"%@&UID=%@&TOKEN=%@",urlStr,[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_ID],[[NSUserDefaults standardUserDefaults] objectForKey:kMY_USER_TOKEN]];
    DDLOG(@"urlStr = %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    __weak ASIHTTPRequest * mrequest = request;
    [request setTimeOutSeconds:12];
    [request setCompletionBlock:^{
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        if (![[tmpDict objectForKey:@"status"] intValue] == 1) {
            DDLOG(@"%@",tmpDict);
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_ID];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_NAME];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_TOKEN];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_IPHONE];
            [[NSUserDefaults standardUserDefaults]removeObjectForKey:kMY_USER_FACE];
//            [NSUserDefaults resetStandardUserDefaults];
        }else{
            if ([tmpDict[@"data"][@"voucher"] intValue]) {
                [XDTools sharedXDTools].haveYouHuiQuan = YES;
            }else{
                [XDTools sharedXDTools].haveYouHuiQuan = NO;
            }
        }
    }];
    [request setFailedBlock:^{
        if (mrequest.error.code == 2) {
//            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request startAsynchronous];
}

- (void)initViewsWithHeight:(float)height{
    CGFloat cheight = iPhone5?143:119;
    
    NSArray * norImgArray;
    NSArray * selImgArray;
    if (iPhone5){
        norImgArray = @[LOADIMAGE(@"sy_i5_01@2x"),LOADIMAGE(@"sy_i5_03@2x"),LOADIMAGE(@"sy_i5_02@2x"),LOADIMAGE(@"sy_i5_04@2x")];
        selImgArray = @[LOADIMAGE(@"sy_i5_sel_01@2x"),LOADIMAGE(@"sy_i5_sel_03@2x"),LOADIMAGE(@"sy_i5_sel_02@2x"),LOADIMAGE(@"sy_i5_sel_04@2x")];
    }else{
        norImgArray = @[LOADIMAGE(@"sy_i4_01@2x"),LOADIMAGE(@"sy_i4_03@2x"),LOADIMAGE(@"sy_i4_02@2x"),LOADIMAGE(@"sy_i4_04@2x")];
        selImgArray = @[LOADIMAGE(@"sy_i4_sel_01@2x"),LOADIMAGE(@"sy_i4_sel_03@2x"),LOADIMAGE(@"sy_i4_sel_02@2x"),LOADIMAGE(@"sy_i4_sel_04@2x")];
    }
    btn1 = [UIButton initButton:CGRectMake(0,height+1, 159, cheight) btnNorImage:[norImgArray firstObject] btnHighlightImage:[selImgArray firstObject] btnTitle:nil titleColor:nil titleFont:nil];
    [btn1 addTarget:self action:@selector(fourBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [backScrollView addSubview:btn1];
    
    btn2 = [UIButton initButton:CGRectMake(0, height_y(btn1)+1, 159, cheight) btnNorImage:[norImgArray objectAtIndex:1] btnHighlightImage:[selImgArray objectAtIndex:1] btnTitle:nil titleColor:nil titleFont:nil];

    [btn2 addTarget:self action:@selector(fourBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [backScrollView addSubview:btn2];

    btn3 = [UIButton initButton:CGRectMake(160, height+1, 160, cheight) btnNorImage:[norImgArray objectAtIndex:2] btnHighlightImage:[selImgArray objectAtIndex:2] btnTitle:nil titleColor:nil titleFont:nil];
    [btn3 addTarget:self action:@selector(fourBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [backScrollView addSubview:btn3];

    btn4 = [UIButton initButton:CGRectMake(160, height_y(btn3)+1, 160, cheight) btnNorImage:[norImgArray objectAtIndex:3] btnHighlightImage:[selImgArray objectAtIndex:3] btnTitle:nil titleColor:nil titleFont:nil];
    [btn4 addTarget:self action:@selector(fourBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [backScrollView addSubview:btn4];

    btn1.tag = 1000;
    btn2.tag = 1001;
    btn3.tag = 1002;
    btn4.tag = 1003;
    

    btn1.backgroundColor = RGBA(114, 192, 112, 1);
    btn2.backgroundColor = RGBA(223, 213, 110, 1);//[UIColor yellowColor];
    btn3.backgroundColor = RGBA(251, 142, 110, 1);//[UIColor redColor];
    btn4.backgroundColor = [UIColor orangeColor];


    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH,self.contentView.frame.size.height);

//    backScrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, height_y(btn4)+3);
    

}

-(void)chooseBtnClick{
    ChooseCityViewController * cvc = [[ChooseCityViewController alloc] init];
    cvc.isComeFromClick = YES;
    
    [self presentViewController:cvc animated:YES completion:^{
        
    }];
}

- (void)fourBtnClicked:(UIButton *)sender
{
    DDLOG_CURRENT_METHOD;
    sender.selected = YES;
    clickcount++;
    if (clickcount>1){
        return;
    }

    switch(sender.tag){
        case 1000:
        {   //作品浏览
            [self performSelector:@selector(gotoShowWorksVC:) withObject:sender afterDelay:0.1];
        }
            break;
        case 1001:
        {   //每时每刻
            [self performSelector:@selector(SynthesizeDetails:) withObject:sender afterDelay:0.1];
        }
            break;
        case 1002:
        {   //预约摄影
            [self performSelector:@selector(AppointmentShoot:) withObject:sender afterDelay:0.1];
        }
            break;
        case 1003:
        {   //选摄影师
            [locService stopUserLocationService];
            locService.delegate = nil;
            [self performSelector:@selector(ChooseCameraManView:) withObject:sender afterDelay:0.1];

        }
            break;
        default:
            break;
    }
}

-(void)gotoShowWorksVC:(UIButton *)sender
{
    ShowWorksViewController * showVC = [[ShowWorksViewController alloc] init];
    [self.navigationController pushViewController:showVC animated:YES];
}

-(void)SynthesizeDetails:(UIButton *)sender
{

    FreePaiViewController * free = [[FreePaiViewController alloc] init];
    [self.navigationController pushViewController:free animated:YES];
}

-(void)AppointmentShoot:(UIButton *)sender
{
    AppointmentShootViewController * appointVC = [[AppointmentShootViewController alloc] init];
    [self.navigationController pushViewController:appointVC animated:YES];
}

-(void)ChooseCameraManView:(UIButton *)sender
{
    ChooseCameraManViewController * chooseCameraMan = [[ChooseCameraManViewController alloc] init];
    chooseCameraMan.type = 1;
    [self.navigationController pushViewController:chooseCameraMan animated:YES];
}

#pragma mark
#pragma mark 点击轮播图 触发事件
-(void)gestureClick:(UITapGestureRecognizer *)sender andUrl:(NSString *)urlString
{
    if(ARRAY_IS_NOT_EMPTY(urlArray)){
        ShowWebViewController * showWebVC = [[ShowWebViewController alloc] init];
        showWebVC.urlstring = [urlArray objectAtIndex:sender.view.tag-10001];
        [self.navigationController pushViewController:showWebVC animated:YES];
    }
}

#pragma mark
#pragma mark  获取首页banner数据
-(void)getBannersData
{
    //type = B 表示首页banner
    NSDictionary * parms = @{@"type":@"B"};
    ASIHTTPRequest * request = [XDTools postRequestWithDict:parms API:homepage_banner];
    __weak ASIHTTPRequest * mrequest = request;
    [request setCompletionBlock:^{
        [XDTools hideProgress:self.contentView];
        NSDictionary * tmpDict = [XDTools JSonFromString:[mrequest responseString]];
        if ([tmpDict[@"status"] intValue]==1){
            [urlArray removeAllObjects];
            NSMutableArray * imgArray = [[NSMutableArray alloc] init];
            for (NSDictionary * dict in tmpDict[@"data"]){
                NSDictionary * cdict;
                if (iPhone5){
                    cdict = @{@"image_url":dict[@"PhotoID"]};
                }else{
                    cdict = @{@"image_url":dict[@"PhotoIDS"]};
                }
                [urlArray addObject:dict[@"Url"]];
                [imgArray addObject:cdict];
            }
            banner.imageUrlArray = [NSMutableArray arrayWithArray:imgArray];
        }else{
            [XDTools showTips:tmpDict[@"msg"] toView:self.view];
        }
    }];
    [request setFailedBlock:^{
        [XDTools hideProgress:self.contentView];
        [XDTools showTips:networkovertime toView:self.view];
    }];
    [request startAsynchronous];
    [XDTools showProgress:self.contentView];
}


#pragma mark 
#pragma mark 百度地图 定位 回调
/**
 *在停止定位后，会调用此函数
 */
- (void)didStopLocatingUser
{
    NSLog(@"停止定位");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude>0&&longitude>0){
        [locService stopUserLocationService];
        [XDTools sharedXDTools].latitude = latitude;
        [XDTools sharedXDTools].longitude = longitude;
        
    }
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
{
    latitude = userLocation.location.coordinate.latitude;
    longitude = userLocation.location.coordinate.longitude;
    if (latitude>0&&longitude>0){
        [locService stopUserLocationService];
        [XDTools sharedXDTools].latitude = latitude;    //经度
        [XDTools sharedXDTools].longitude = longitude;  //纬度
        
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%f",latitude] forKey:@"latitude"];
        [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%f",longitude] forKey:@"longitude"];
        
        
        if (![[NSUserDefaults standardUserDefaults] objectForKey:ISFIRSTSTART]){
            ChooseCityViewController * cvc = [[ChooseCityViewController alloc] init];
            cvc.isEnterFromFirstVC = YES;
            
            [self presentViewController:cvc animated:YES completion:^{
                
            }];
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:ISFIRSTSTART];
            
        }
    }
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:ISFIRSTSTART];
}


//版本更新
-(void)updateVerson{
    
    if(![XDTools NetworkReachable]){
        [XDTools showTips:brokenNetwork toView:self.view];
        return;
    }
    
    ASIHTTPRequest * request =[XDTools postRequestWithDict:@{@"Type":@"ios"} API:API_GETVERSION] ;
    
    __weak ASIHTTPRequest * mrequest = request;
    
    [request setCompletionBlock:^{
        
        NSDictionary * tmpDict= [XDTools JSonFromString:mrequest.responseString];
        NSDictionary * returnDict =[tmpDict valueForKey:@"data"];
        NSString * newVersion =[NSString stringWithFormat:@"%@",returnDict[@"Version"]];
        NSString *oldVerson = [[NSString alloc] initWithString:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
        if ([newVersion isEqualToString:oldVerson]){
            return;
        }
        downUrl =[returnDict objectForKey:@"Url"];
        if (0) {
            UIAlertView *alertForce = [[UIAlertView alloc]initWithTitle:@"版本更新" message:[returnDict objectForKey:@"Remark"]  delegate:self cancelButtonTitle:nil otherButtonTitles:@"更新", nil];
            alertForce.tag = 110;
            [alertForce show];
        }else{
            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:[returnDict objectForKey:@"Remark"] delegate:self cancelButtonTitle:@"立即更新" otherButtonTitles:@"忽略本次", nil];
            al.tag = 222;
            
            for (UIView *view in al.subviews) {
                if ([view isKindOfClass:[UILabel class]]) {
                    
                    UILabel *labe = (UILabel *)view;
                    
                    labe.textAlignment = NSTextAlignmentLeft;
                }
            }
            [al show];
            
        }
        
    }];
    
    [request setFailedBlock:^{
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    [request setTimeOutSeconds:12];
    [request startAsynchronous];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 222){
        if (buttonIndex == 0) {
            NSURL *url = [NSURL URLWithString:downUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
    }else if (alertView.tag == 110){
        if (buttonIndex == 0) {
            NSURL *url = [NSURL URLWithString:downUrl];
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
